package com.wn.main

import android.content.Context
import android.content.Intent
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.wn.common.constant.KEY_INDEX
import com.wn.common.constant.MAIN_ACTIVITY_HOME
import com.wn.framework.base.BaseActivity
import com.wn.framework.utils.AppExit
import com.wn.framework.utils.StatusBarSettingHelper
import com.wn.main.databinding.ActivityMainBinding
import com.wn.main.navigator.WnFragmentNavigator
import dagger.hilt.android.AndroidEntryPoint

/**
 * @Author: wn
 * @Date: 2024/9/3 16:26
 * @Description: 主页
 */
@Route(path = MAIN_ACTIVITY_HOME)
@AndroidEntryPoint
class MainActivity : BaseActivity<ActivityMainBinding>() {

  override fun getLayoutRes() = R.layout.activity_main

  private lateinit var navController: NavController

  override fun initView() {
    super.initView()
    /**
     * FragmentContainerView 与 BottomNavigationView 联动
     * 注意: menu 与 navigation 中 android:id="@+id/nav_home" 必须保持一致
     */
    // 1.寻找出路由控制器对象，它是路由跳转的唯一入口，找到宿主NavHostFragment
    val navHostFragment =
      supportFragmentManager.findFragmentById(R.id.nav_host_fragment_activity_main) as NavHostFragment
    navController = navHostFragment.navController
    // 2.自定义FragmentNavigator，mobile_navigation.xml文件中的fragment标识改为 WnFragmentNavigator 中 @Navigator.Name("wnFragment")
    val wnFragmentNavigator =
      WnFragmentNavigator(this, navHostFragment.childFragmentManager, navHostFragment.id)
    // 3.注册到Navigator里面，这样才找得到
    navController.navigatorProvider.addNavigator(wnFragmentNavigator)
    // 4.设置Graph，需要将activity_main.xml文件中的app:navGraph="@navigation/mobile_navigation"移除
    navController.setGraph(R.navigation.mobile_navigation)
    // 5.将 NavController和 BottomNavigationView 绑定，形成联动效果
    mBinding.navView.setupWithNavController(navController)

    StatusBarSettingHelper.setStatusBarTranslucent(this)
    StatusBarSettingHelper.statusBarLightMode(this, true)
  }

  /**
   * 接收 欢迎页面  跳转过来携带的数据 index
   */
  override fun onNewIntent(intent: Intent?) {
    super.onNewIntent(intent)
    intent?.apply {
      val index = getIntExtra(KEY_INDEX, 0)
    }
  }

  /**
   * 在按一次退出程序
   */
  @Deprecated(
    "Deprecated in Java",
    ReplaceWith("super.onBackPressed()", "com.wn.framework.base.BaseActivity")
  )
  override fun onBackPressed() {
    AppExit.onBackPressed(
      this,
      { ToastUtils.showShort(com.wn.framework.R.string.base_app_exit_one_more_press) }
    )
  }

  companion object {
    fun start(context: Context, index: Int = 0) {
      val intent = Intent(context, MainActivity::class.java)
      intent.putExtra(KEY_INDEX, index)
      context.startActivity(intent)
    }
  }
}